<?php

namespace app\admin\behavior;

use think\Request;
use think\facade\Session;
use think\Db;

/**
 *  run 方法在没有制定特别的标签名称 作为默认的执行方法体
 *  如果定义了制定标签的方法体 那么会执行同名的方法体
 */
class AuthFilter
{
    public function run(Request $request,$params)
    {
        $token=$request->header("Token",null);
        
        $user = json_decode(base64_decode(decrypt($token)));
        if (empty($user)) return; //用户没有登录

        $hasSid=property_exists($user,"sid");
        if($hasSid && $token == Session::get($user->sid)){
            $request->user = $user;
            $result = Db::query('select DISTINCT p.`key` from zbc_shop_manager_user_role as ur join zbc_shop_manager_role as r on ur.roleId = r.id join zbc_shop_manager_role_permission as rp on r.id = rp.roleId join zbc_shop_manager_permission as p on rp.permissionId = p.id where ur.userId = ?', [$user->id]);
            $permissions = [];
            foreach($result as $val){
                array_push($permissions,$val['key']);
            }
            Session::set('permissions', $permissions);
        }
    }
}
